package com.audaque.springboot.foshanupload.jwtcore.component;


import com.audaque.springboot.foshanupload.jwtcore.util.encode.rsaPem.RsaPem;

import com.audaque.springboot.foshanupload.jwtcore.util.encode.rsaPem.RsaUtil;
import com.audaque.springboot.foshanupload.jwtcore.properties.JwtProperties;
import com.google.common.base.Objects;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author zgb
 * @desc ...
 * @date 2022-11-23 17:39:08
 */
@Component
@Slf4j
public class RsaUtilExtProvider {
    /**
     * Java中变量初始化顺序为：
     * 静态变量或静态语句块(按声明顺序)–> 非静态变量或构造代码块(按声明顺序)–> 构造方法 –> @Value/@Autowired等
     * 如果想要为静态成员变量自动赋值，可以使用@Autowired作用在set方法上来进行注入
     */
    //静态方法可以给new时候使用而不需要关注bean的顺序
    private static String pem_pkcs1_prv;

    private static String pem_pkcs1_pub;


    private static RsaUtil rsaUtil;


    @Autowired
    public void setPem_pkcs1_prv(JwtProperties jwtPropertiese) {
        this.pem_pkcs1_prv = jwtPropertiese.getPrivateKey();
    }

    @Autowired
    public void setPem_pkcs1_pub(JwtProperties jwtPropertiese) {
        this.pem_pkcs1_pub = jwtPropertiese.getPublicKey();
    }


    @Autowired
    public void setRsaUtil(JwtProperties jwtPropertiese) {
        try {
            RsaPem rsaPem = RsaPem.FromPEM(jwtPropertiese.getPrivateKey());
            this.rsaUtil = new RsaUtil(rsaPem);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public  boolean validJwtProperties() {
        RsaPem pem = rsaUtil.ToPEM(false);

        String pem_pkcs1_prv_copy = null;
        String pem_pkcs1_pub_copy = null;
        try {
            pem_pkcs1_prv_copy = pem.ToPEM_PKCS1(false);
            pem_pkcs1_pub_copy = pem.ToPEM_PKCS1(true);
        } catch (Exception e) {
            return false;
        }

        if (!(Objects.equal(pem_pkcs1_pub,pem_pkcs1_pub_copy) && Objects.equal(pem_pkcs1_prv,pem_pkcs1_prv_copy))) {
            return false;
        }
        return true;
    }

    public static  String encode(String str) throws Exception {
        log.debug("pem_pkcs1_prv:" + pem_pkcs1_prv);
        log.debug("pem_pkcs1_pub:" + pem_pkcs1_pub);
        log.debug("rsaUtil:" + rsaUtil);
        String encode = rsaUtil.Encode(str);
        log.debug("encode:" + encode);
        return encode;
    }

    public static String decode(String en) throws Exception {
        String decode = rsaUtil.Decode(en);
        log.debug("decode:" + decode);
        return decode;
    }


}
